#!/usr/bin/env python
################################################################################
#            __  __            _   ____        _ _ ____        _              #
#           |  \/  | ___  __ _| |_| __ )  __ _| | | __ )  ___ | |_           #
#           | |\/| |/ _ \/ _` | __|  _ \ / _` | | |  _ \ / _ \| __|         #
#           | |  | |  __/ (_| | |_| |_) | (_| | | | |_) | (_) | |_          #
#           |_|  |_|\___|\__,_|\__|____/ \__,_|_|_|____/ \___/ \__|          #
#                                                                             #
#                                     by                                       #
# _______ .______       _______  _______   ______   ______    _______   _______ #
#|   ____||   _  \     |   ____||   ____| /      | /  __  \  |       \ |   ____| #
#|  |__   |  |_)  |    |  |__   |  |__   |  ,----'|  |  |  | |  .--.  ||  |__     #
#|   __|  |      /     |   __|  |   __|  |  |     |  |  |  | |  |  |  ||   __|     #
#|  |     |  |\  \----.|  |____ |  |____ |  `----.|  `--'  | |  '--'  ||  |____     #
#|__|     | _| `._____||_______||_______| \______| \______/  |_______/ |_______|   #
#                                                                                 #
#                          Channel Management Module                             #
#                             Modular FrameWork                                 #
#
# Coders
#
#	Justin Giorgi (rebel_kid)
#
# Debuggers
#
#	Justin Giorgi (rebel_kid)
#	Lachlan Gilmour (chilli0)
#	David Liedle (spiderbyte)
#	(Polarina)
#	(prologic)
#
################################################################################
#                                                                              #
#                               GPL Licensed                                   #
#                                                                              #
################################################################################

# Imports
import time

# Variables
version = 90

# Calculates internet time
def beats(globalvars, msgvars):

	beatsnow = int((((time.gmtime()[3] + 1) * 3600) + (time.gmtime()[4] * 60) + time.gmtime()[5]) / 86.4)
	if beatsnow > 999:
		beatsnow = beatsnow - 1000
	msgvars["server"].privmsg(msgvars["destination"], 'It is @%s.beats!' % (str(beatsnow)))

# Adds requests to the database
def request(globalvars, msgvars):

	# Returns request submitted and inserts request into table
	globalvars["cursor"].execute("insert into request (source, request) values (%s, %s)", (msgvars["source"], ' '.join(msgvars["command"][1:])))
	msgvars["server"].privmsg(msgvars["destination"], "%s: I'll get someone right on it." % (msgvars["source"]))

# Provides bot statistics
def stats(globalvars, msgvars):
	
	# Variables
	days = int((time.time() - globalvars["starttime"]) / 86400)
	hours = int(((time.time() - globalvars["starttime"]) - (days * 86400)) / 3600)
	minutes = int(((time.time() - globalvars["starttime"]) - (days * 86400 + hours * 3600)) / 60)
	seconds = int(time.time() - globalvars["starttime"]) - (days * 86400 + hours * 3600 + minutes * 60)
	
	# Time processing
	if (time.time() - globalvars["starttime"]) / 60 <= 1:
		online = "I have been online for %s seconds." % (str(seconds))
	elif (time.time() - globalvars["starttime"]) / 3600 <= 1:
		online = "I have been online for %s minutes and %s seconds." % (str(minutes), str(seconds))
	elif (time.time() - globalvars["starttime"]) / 86400 <= 1:
		online = "I have been online for %s hours %s minutes and %s seconds." % (str(hours), str(minutes), str(seconds))
	else:
		online = "I have been online for %s days %s hours %s minutes and %s seconds." % (str(days), str(hours), str(minutes), str(seconds))
	
	# Channel and network counting
	globalvars["cursor"].execute("select count(*) from channels");
	chans = globalvars["cursor"].fetchone()
	globalvars["cursor"].execute("select count(*) from networks");
	nets = globalvars["cursor"].fetchone()
	
	# Stats declaration
 	msgvars["server"].privmsg(msgvars["destination"], "I'm MeatBallBot revision: %s. I am currently running in %s channels on %s networks. %s" % (version, str(chans[0]), str(nets[0]), online))
	
# Joins newly added channels and parts deleted ones
def joinpartchans(globalvars, msgvars):

	# Finds the channels in the database for the current server
	globalvars["cursor"].execute("select channame, netid from channels")
	dbchans = globalvars["cursor"].fetchall()
	dbchannames = []
	for channel in dbchans:
		if msgvars["server"] == globalvars["servers"][channel[1] - 1]:
			dbchannames.append(channel[0])

	# Finds the channels in joindchans for the current server
	joinedchannames = []
	for channel in globalvars["joinedchannels"]:
		if msgvars["server"] == globalvars["servers"][channel[1] - 1]:
			joinedchannames.append(channel[0])

	# Parts channels that are no longer in the database
	for channel in globalvars["joinedchannels"]:
			if channel[0] not in dbchannames:
				msgvars["server"].part(channel[0])

	# Join channels added to the database
	for channel in dbchans:
			if channel[0] not in joinedchannames:
				msgvars["server"].join(channel[0])

	# Refreshes joinedchans
	globalvars["joinedchans"] = dbchans
	
def autoload(globalvars):
	
	# Loads oncall
	oncall = {'beats':beats, 'request':request, 'stats':stats}
	for feature in oncall.items():
		if feature[0] not in globalvars["oncall"].keys():
			globalvars["oncall"][feature[0]] = feature[1]
	
	# Loads privmsg
	privmsg = {'join':joinpartchans, 'part':joinpartchans}
	for feature in privmsg.items():
		if feature[0] not in globalvars["privmsg"].keys():
			globalvars["privmsg"][feature[0]] = feature[1]
	
def load(globalvars, msgvars):
	
	# Loads oncall
	oncall = {'beats':beats, 'request':request, 'stats':stats}
	for feature in oncall.items():
		if feature[0] not in globalvars["oncall"].keys():
			globalvars["oncall"][feature[0]] = feature[1]
		else:
			msgvars["server"].privmsg(msgvars["destination"], "There is already a function named %s." % (feature[0]))
	
	# Loads privmsg
	privmsg = {'join':joinpartchans, 'part':joinpartchans}
	for feature in privmsg.items():
		if feature[0] not in globalvars["privmsg"].keys():
			globalvars["privmsg"][feature[0]] = feature[1]
		else:
			msgvars["server"].privmsg(msgvars["destination"], "There is already a function named %s." % (feature[0]))
	return True
			
def unload(globalvars, msgvars, reloadmodule = False):
	
	# Unloads oncall
	oncall = {'beats':beats, 'request':request, 'stats':stats}
	for feature in oncall.items():
		if feature[0] in globalvars["oncall"].keys():
			del globalvars["oncall"][feature[0]]
		else:
			msgvars["server"].privmsg(msgvars["destination"], "I have no clue what just happened.")
	
	# Unloads privmsg
	privmsg = {'join':joinpartchans, 'part':joinpartchans}
	for feature in privmsg.items():
		if feature[0] in globalvars["privmsg"].keys():
			del globalvars["privmsg"][feature[0]]
	return True
